<template>
  <div class="trouble-sidebar">
    <div class="sidebar-header">
      <h3 class="sidebar-title">故障列表</h3>
      <button
        class="toggle-button"
        :class="{ 'toggle-button-collapsed': isCollapsed }"
        @click="toggleCollapse"
        :title="isCollapsed ? '展开侧边栏' : '收起侧边栏'"
      >
        {{ isCollapsed ? ">>" : "<<" }}
      </button>
    </div>

    <div class="sidebar-content" :class="{ collapsed: isCollapsed }">
      <ul class="menu-list">
        <li
          v-for="(item, index) in menuItems"
          :key="`main-${index}`"
          class="menu-item"
        >
          <div
            class="menu-item-header"
            @click="toggleMenuItem(item)"
            :class="{ active: isItemActive(item) }"
          >
            <span class="menu-icon">{{ getMenuIcon(item.icon) }}</span>
            <span class="menu-title" v-if="!isCollapsed">{{ item.title }}</span>
            <span
              class="expand-icon"
              v-if="!isCollapsed && item.children && item.children.length > 0"
            >
              {{ isExpanded(item.id) ? "▼" : "▶" }}
            </span>
          </div>

          <ul
            v-if="
              item.children && item.children.length > 0 && isExpanded(item.id)
            "
            class="submenu-list"
          >
            <li
              v-for="(child, childIndex) in item.children"
              :key="`child-${index}-${childIndex}`"
              class="submenu-item"
            >
              <div
                class="submenu-item-header"
                @click="selectTrouble(child)"
                :class="{ active: isItemActive(child) }"
              >
                <span class="menu-icon">{{ getMenuIcon(child.icon) }}</span>
                <!-- 自定义单选框 -->
                <div
                  class="custom-radio"
                  :class="{ checked: isItemActive(child) }"
                >
                  <span v-if="isItemActive(child)" class="radio-check">✓</span>
                </div>
                <span class="menu-title">{{ child.title }}</span>
                <!-- 当选中运行过载故障时，显示调节负载按钮 -->
                <button
                  v-if="child.id === 'overload' && isOverloadSelected"
                  class="adjust-load-btn"
                  @click.stop="openLoadAdjustmentPanel"
                  title="调节负载"
                >
                  故障排查
                </button>
                <!-- 当选中水流量偏低故障时，显示调节水流量按钮 -->
                <button
                  v-if="child.id === 'low-water-flow' && isLowWaterFlowSelected"
                  class="adjust-load-btn"
                  @click.stop="openWaterFlowAdjustmentPanel"
                  title="调节水流量"
                >
                  故障排查
                </button>
                <!-- 当选中风路堵塞故障时，显示清理风道按钮 -->
                <button
                  v-if="
                    child.id === 'airway-blocked' && isAirwayBlockedSelected
                  "
                  class="adjust-load-btn airway-clean-btn"
                  @click.stop="openAirwayCleanPanel"
                  title="清理风道"
                >
                  故障排查
                </button>
                <!-- 当选中PTC接触不良故障时，显示重新接线按钮 -->
                <button
                  v-if="
                    child.id === 'ptc-poor-contact' && isPtcContactPoorSelected
                  "
                  class="adjust-load-btn ptc-rewire-btn"
                  @click.stop="openPTCRewirePanel"
                  title="重新接线"
                >
                  故障排查
                </button>
                <!-- 当选中PTC损坏故障时，显示更换备用PTC按钮 -->
                <button
                  v-if="child.id === 'ptc-damage' && isPtcDamageSelected"
                  class="adjust-load-btn ptc-recovery-btn"
                  @click.stop="openPTCRecoveryPanel"
                  title="更换备用PTC"
                >
                  故障排查
                </button>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { setAlgorithmParam } from "@/api/util";
import { useUserStore } from "@/store/user";
import sendToUnity from "@/core/communication/SendToUnity";
import { SendMessageType } from "@/core/config/DeclareGlobal";

// 获取用户store实例
const userStore = useUserStore();

// 定义组件事件
const emit = defineEmits(["trouble-selected", "openPanel"]);

// 侧边栏状态
const isCollapsed = ref(false);
const expandedItems = ref(new Set());
const selectedTrouble = ref(null);

// 判断当前是否选中了运行过载故障
const isOverloadSelected = ref(false);
// 判断当前是否选中了水流量偏低故障
const isLowWaterFlowSelected = ref(false);
// 判断当前是否选中了风路堵塞故障
const isAirwayBlockedSelected = ref(false);
// 判断当前是否选中了PTC接触不良故障
const isPtcContactPoorSelected = ref(false);
// 判断当前是否选中了PTC损坏故障
const isPtcDamageSelected = ref(false);

// 故障菜单项数据（从store迁移到组件内部）
const menuItems = ref([
  {
    id: "basic-principles",
    title: "发电机定子绕阻温度高报警（PTC145）",
    icon: "Document",
    children: [
      {
        id: "overload",
        title: "运行过载",
        icon: "Notebook",
        children: [],
        // 添加选中时触发的函数属性
        onSelect: (trouble) => {
          // 从user store获取copyNum
          const copyNum = userStore.copyNum;
          // 发送util里的设置算法的方法，传入copyNum参数
          setAlgorithmParam("2_18_0_0", 1, copyNum);
          // 设置过载选中状态
          isOverloadSelected.value = true;
          // // 模拟过载后自动打开调节面板
          // setTimeout(() => {
          //   openLoadAdjustmentPanel();
          // }, 1000);
          // ElMessage.success("运行过载状态已模拟");
        },
      },
      {
        id: "low-water-flow",
        title: "水流量偏低",
        icon: "DataAnalysis",
        children: [],
        onSelect: (trouble) => {
          // 从user store获取copyNum
          const copyNum = userStore.copyNum;
          console.log(`选中故障：${trouble.title}`);
          // 模拟水流量偏低状态
          setAlgorithmParam("2_41_0_0", 0, copyNum); // 设置为30，低于报警阈值50
          // 设置水流量偏低选中状态
          isLowWaterFlowSelected.value = true;
          // // 模拟后自动打开调节面板
          // setTimeout(() => {
          //   openWaterFlowAdjustmentPanel();
          // }, 1000);
          // ElMessage.warning("水流量偏低状态已模拟，低于报警阈值50 L/min");
        },
      },
      {
        id: "airway-blocked",
        title: "风路堵塞",
        icon: "Fan",
        children: [],
        onSelect: (trouble) => {
          // 从user store获取copyNum
          const copyNum = userStore.copyNum;
          console.log(`选中故障：${trouble.title}`);
          // 模拟风路堵塞状态，设置所有四路风量参数为1.5（低于报警阈值2）
          const airflowParams = [
            "2_38_0_0",
            "2_39_0_0",
            "2_40_0_0",
            "2_36_0_0",
          ];
          airflowParams.forEach((param) => {
            setAlgorithmParam(param, 0.1, copyNum);
          });
          // 设置风路堵塞选中状态
          isAirwayBlockedSelected.value = true;
          sendToUnity.send({
            type: SendMessageType.WindRoadBlock,
            data: {},
          });
          // // 模拟后自动打开清理面板
          // setTimeout(() => {
          //   openAirwayCleanPanel();
          // }, 1000);
          // ElMessage.warning("风路堵塞状态已模拟，四路风量均低于报警阈值");
        },
      },
      {
        id: "ptc-poor-contact",
        title: "PTC线路接触不良",
        icon: "Temperature",
        children: [],
        onSelect: (trouble) => {
          // 从user store获取copyNum
          const copyNum = userStore.copyNum;
          console.log(`选中故障：${trouble.title}`);
          // 模拟PTC接触不良状态
          setAlgorithmParam("2_43_0_0", 0, copyNum);
          // 设置PTC接触不良选中状态
          isPtcContactPoorSelected.value = true;
          // // 模拟后自动打开调节面板
          // setTimeout(() => {
          //   openPTCRewirePanel();
          // }, 1000);
          // ElMessage.warning("PTC接触不良状态已模拟");
        },
      },
      {
        id: "ptc-damage",
        title: "PTC损坏",
        icon: "Warning",
        children: [],
        onSelect: (trouble) => {
          // 从user store获取copyNum
          const copyNum = userStore.copyNum || 5; // 默认值为5
          console.log(`选中故障：${trouble.title}`);
          // 模拟PTC损坏状态
          setAlgorithmParam("2_43_0_0", 0, copyNum);
          // 设置PTC损坏选中状态
          isPtcDamageSelected.value = true;
          // // 模拟后自动打开更换面板
          // setTimeout(() => {
          //   openPTCRecoveryPanel();
          // }, 1000);
          // ElMessage.warning("PTC损坏状态已模拟");
        },
      },
      {
        id: "random-trouble",
        title: "随机故障注入",
        icon: "Random",
        children: [],
        onSelect: async (trouble) => {
          console.log(`选中故障：${trouble.title}`);
          // 收集所有可用故障（排除随机故障注入自身）
          const allTroubles = menuItems.value
            .flatMap((item) => item.children || [])
            .filter((t) => t.id !== "random-trouble");
          if (allTroubles.length > 0) {
            // 随机选择一项故障
            const randomIndex = Math.floor(Math.random() * allTroubles.length);
            const selectedRandomTrouble = allTroubles[randomIndex];
            console.log(`随机选择的故障：${selectedRandomTrouble.title}`);

            // 触发随机选择的故障
            if (
              selectedRandomTrouble.onSelect &&
              typeof selectedRandomTrouble.onSelect === "function"
            ) {
              try {
                selectedRandomTrouble.onSelect(selectedRandomTrouble);
              } catch (err) {
                console.error(
                  `执行随机选择的故障项${selectedRandomTrouble.id}的onSelect函数时出错:`,
                  err
                );
              }
            }

            // 显示消息提示
            ElMessage.success(`注入故障成功`);
          }
        },
      },
    ],
  },
]);

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 切换菜单项展开/收起
const toggleMenuItem = (item) => {
  if (item.children && item.children.length > 0) {
    if (expandedItems.value.has(item.id)) {
      expandedItems.value.delete(item.id);
    } else {
      expandedItems.value.add(item.id);
    }
  } else {
    // 如果没有子项，直接选中
    selectTrouble(item);
  }
};

// 检查菜单项是否展开
const isExpanded = (id) => {
  return expandedItems.value.has(id);
};

// 选中故障项
const selectTrouble = async (trouble) => {
  // 如果已经是选中状态，不需要重复操作
  if (isItemActive(trouble)) {
    return;
  }

  try {
    // 显示确认弹窗
    const result = await ElMessageBox.confirm(
      "是否启动该故障模拟",
      "确认操作",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    if (result === "confirm") {
      // 用户确认后选择故障
      selectedTrouble.value = trouble;

      // 触发该故障项的onSelect函数（如果存在）
      if (trouble.onSelect && typeof trouble.onSelect === "function") {
        try {
          trouble.onSelect(trouble);
        } catch (err) {
          console.error(`执行故障项${trouble.id}的onSelect函数时出错:`, err);
        }
      }

      emit("trouble-selected", trouble);
    }
  } catch (error) {
    // 用户取消操作，不做任何处理
    console.log("用户取消了故障模拟启动");
  }
};

// 检查菜单项是否为当前选中项
const isItemActive = (item) => {
  return selectedTrouble.value && selectedTrouble.value.id === item.id;
};

// 打开负载调节面板
const openLoadAdjustmentPanel = () => {
  // 触发打开FloatingPanel并显示负载调节组件
  emit("openPanel", "负载调节");
};

// 打开水流量调节面板
const openWaterFlowAdjustmentPanel = () => {
  // 触发打开FloatingPanel并显示水流量调节组件
  emit("openPanel", "水流量调节");
};

// 打开风道清理面板
const openAirwayCleanPanel = () => {
  // 触发打开FloatingPanel并显示风道清理组件
  emit("openPanel", "风道清理");
};

// 打开PTC重新接线面板
const openPTCRewirePanel = () => {
  // 触发打开FloatingPanel并显示PTC重新接线组件
  emit("openPanel", "PTC重新接线");
};

// 打开PTC更换面板
const openPTCRecoveryPanel = () => {
  // 触发打开FloatingPanel并显示PTC更换组件
  emit("openPanel", "PTC更换");
};

// 获取菜单图标（使用emoji作为占位符，实际项目中可替换为组件库图标）
const getMenuIcon = (iconName) => {
  const iconMap = {
    Document: "📄",
    Notebook: "📝",
    DataAnalysis: "📊",
    View: "👁️",
    Temperature: "🌡️",
    Warning: "⚠️",
    Random: "🎲",
  };
  return iconMap[iconName] || "📋";
};
</script>

<style scoped>
.trouble-sidebar {
  height: 100%;
  background-color: #22474f;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  color: #ffffff;
}

.sidebar-header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  background-color: #22474f;
  position: relative;
}

.sidebar-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
  flex: 1;
}

.toggle-button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  color: #ffffff;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
}

.toggle-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.toggle-button {
  transition: color 0.3s ease;
}

.toggle-button-collapsed {
  color: #e1612e;
  transition: color 0.3s ease;
}

.toggle-button-collapsed:hover {
  color: #bb7151;
  background-color: rgba(255, 255, 255, 0.1);
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
  transition: width 0.3s ease;
  width: 280px;
}

.sidebar-content.collapsed {
  width: 60px;
}

.menu-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.menu-item {
  margin-bottom: 4px;
}

.menu-item-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border: none;
  background: none;
  width: 100%;
  text-align: left;
  transition: all 0.3s ease;
  border-radius: 4px;
  margin: 2px 8px;
  color: #ffffff;
}

.menu-item-header:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.menu-item-header.active {
  background-color: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.submenu-list {
  list-style: none;
  padding: 0;
  margin: 0;
  padding-left: 16px;
}

.submenu-item {
  margin-bottom: 2px;
}

.submenu-item-header {
  display: flex;
  align-items: center;
  padding: 8px 16px 8px 24px;
  cursor: pointer;
  border: none;
  background: none;
  width: 100%;
  text-align: left;
  transition: all 0.3s ease;
  border-radius: 4px;
  margin: 2px 8px;
  font-size: 14px;
  color: #ffffff;
}

.submenu-item-header:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.submenu-item-header.active {
  background-color: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.menu-icon {
  margin-right: 8px;
  font-size: 16px;
  width: 20px;
  text-align: center;
  color: #ffffff;
}

/* 自定义单选框样式 */
.custom-radio {
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.custom-radio.checked {
  background-color: #409eff;
  border-color: #409eff;
}

.radio-check {
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
  line-height: 1;
}

.menu-title {
  flex: 1;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #ffffff;
}

/* 调节负载按钮样式 */
.adjust-load-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
  margin-left: 8px;
}

.adjust-load-btn:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.adjust-load-btn:active {
  background-color: #3a8ee6;
}

/* 清理风道按钮样式 - 特殊视觉标识 */
.airway-clean-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  animation: pulse 2s infinite;
}

.airway-clean-btn:hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.4);
}

/* PTC重新接线按钮样式 */
.ptc-rewire-btn {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  animation: pulse-orange 2s infinite;
}

.ptc-rewire-btn:hover {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  box-shadow: 0 2px 8px rgba(245, 158, 11, 0.4);
}

/* PTC更换备用组件按钮样式 */
.ptc-recovery-btn {
  background: linear-gradient(135deg, #a855f7 0%, #9333ea 100%);
  animation: pulse-purple 2s infinite;
}

.ptc-recovery-btn:hover {
  background: linear-gradient(135deg, #9333ea 0%, #7e22ce 100%);
  box-shadow: 0 2px 8px rgba(168, 85, 247, 0.4);
}

/* 脉冲动画效果 - 紫色 */
@keyframes pulse-purple {
  0% {
    box-shadow: 0 0 0 0 rgba(168, 85, 247, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(168, 85, 247, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(168, 85, 247, 0);
  }
}

/* 脉冲动画效果 - 红色 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
  }
}

/* 脉冲动画效果 - 橙色 */
@keyframes pulse-orange {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 158, 11, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 158, 11, 0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .adjust-load-btn {
    padding: 4px 8px;
    font-size: 11px;
  }
}

.expand-icon {
  font-size: 12px;
  color: #ffffff;
  transition: transform 0.3s ease;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar-content {
    width: 240px;
  }

  .sidebar-content.collapsed {
    width: 50px;
  }

  .menu-title {
    font-size: 13px;
  }
}

/* 滚动条样式 */
.sidebar-content::-webkit-scrollbar {
  width: 4px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 2px;
}

.sidebar-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>